// index.js
// 获取应用实例
const app = getApp()
Page({
  data: {
    city: '杭州',
    today: {},
    weater:[],
    _city: '',
    updateTime: '',
    hours: []
  },
  // 获取天气数据
  getWeaterData: function(city) {
    wx.showToast({  // 显示加载动画
      title: '数据加载中...',
      icon: 'loading',
      mask: true
    });
    wx.request({
      url: 'https://www.tianqiapi.com/api?version=v1&appid=56576926&appsecret=dV7FlVBH',
      // url: 'https://www.tianqiapi.com/api?version=v1&appid=82152832&appsecret=Uy5suObR',
      // url: 'https://www.tianqiapi.com/api?version=v1&appid=14811412&appsecret=z9Whld0k',
      // url:'https://www.tianqiapi.com/api?version=v1&appid=51348694&appsecret=jsHv88TB',
      data: {
        city: city
      },
      success:(res)=> {
        wx.stopPullDownRefresh();  // 关闭下拉刷新
        let city = res.data.city;
        let weater = res.data.data;
        if (!weater) {
          wx.showToast({
            title: '数据加载失败',
            icon: 'error'
          })
          return;
        }
        let today = weater.splice(0, 1)[0];
        let hours = today.hours;  // 未来24小时数据
        let tomorrowHours = weater[0].hours;
        let hourNum = hours.length;
        let _len = 24 - hourNum;
        for (let i = 0; i < _len; i++) {
          hours.push(tomorrowHours[i])
        }
        this.setData({
            updateTime: res.data.update_time.substring(11),
            today: today,
            weater:weater,
            city: city,
            hours: hours,
        })
        wx.hideToast();
      },
      fail: (err) => {
        console.log(err)
        wx.stopPullDownRefresh();
        wx.hideToast();
        wx.showToast({  // 没有网络时
          icon: 'error',
          title: '请检查网络设置',
          duration: 2000
        })
      }
    });
  },
  // 搜索城市
  searchCity: function() {
    if (this.data._city.trim().length <= 0) {
      this.setData({_city: ''});
      return;
    }
    this.getWeaterData(this.data._city);
    this.setData({
      _city: ''
    });
  },
  // 获取用户定位信息
  getUserLocation: function() {
    wx.showLoading({
      title: '正在定位...',
      icon: 'loading'
    })
    wx.getLocation({
      type: 'gcj02',
      success: (res) => {
        console.log('res',res)
        let locationStr = res.latitude + ',' + res.longitude;
        this.getCity(locationStr);
      },
      fail: (res) => {
        console.log(res)
        wx.showModal({
          title: '定位失败',
          content: '请确认打开了手机定位服务，并且给微信提供了授权。若不提供定位，将默认显示北京天气数据。',
          showCancel: false
        });
        this.getWeaterData('北京')
      }
    })
  },
  // 获取城市信息
  getCity: function(locationStr) {
    wx.showToast({
      title: '正在定位...',
      icon: 'loading'
    })
    wx.request({
      url: 'https://apis.map.qq.com/ws/geocoder/v1/?l&get_poi=1',
      data:{
        "key": "ADQBZ-LPELK-BKRJA-A2FFS-RU7PE-CJBOP",
        "location": locationStr
      },
      method:'Get',
      success: res => {
        console.log('city---',res)
        let _city = res.data.result.address_component.city;
        let district = res.data.result.address_component.district;
        let city = _city.replace('市', '');
        this.getWeaterData(city);
      },
      fail: res => {
        console.log('--getCityFail',res)
        wx.showModal({
          title: '定位失败',
          content: '请确认打开了手机定位服务，并且给微信提供了授权。若不提供定位，将默认显示北京天气数据。',
          showCancel: false
        });
        this.getWeaterData('北京')
      }
    })
  },
  onLoad() {
    // return;
    this.getUserLocation();
  },
  // 下拉刷新
  onPullDownRefresh () {
    this.getWeaterData(this.data.city);
    wx.setBackgroundTextStyle({
      textStyle: 'dark' // 下拉背景字体、loading 图的样式为dark
    })
  },
  getLocationFail: function() {
    wx.showModal({
      title: '定位失败',
      content: '请确认打开了手机定位服务，并且给微信提供了授权。若不提供定位，将默认显示北京天气数据。',
      cancelText: false
    });
    this.getWeaterData('北京')
  }
})
